const fetch = require("../../../locale/fetch.js")
const util = require('../../../utils/util.js')
const formatNumber = util.formatNumber
const getRandom = util.getRandom
const app = getApp()
Page({
  data: {
    first: true, //只在第一次提示
    height: "",
    //页面显示座位
    seat: [],
    //原有座位
    seats: [],
    lineTop: 0,
    lineHeight: "",
    lineArray: [],
    columnNumber: 0,
    //选择的座位
    selectSeatList: [],
    maxSelect: 0,
    totalMoney: "",
    totalMoneyFloat: 0.00,
    movie: {},
    price: 0,
    info: {},
    scaleValue: 0.6,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 页面跳转传参：电影票价格，电影信息
    const cinema = JSON.parse(options.cinema)
    const movie = JSON.parse(options.movie);
    const info = JSON.parse(options.info)
    const time = new Date(info.showDate + ' ' + info.showTime)
    info.showTime = (time.getMonth() + 1) + '月' + time.getDate() + '日 '
      + time.getHours() + ':' + time.getMinutes() + ":" + time.getSeconds()
    this.setData({
      info: info,
      movie: movie,
      cinemaDetail: cinema
    })
    var that = this;
    wx.showLoading()
    new Promise((resolve, reject) => {
      wx.request({
        url: app.globalData.url + `/movie/queryShowSeats?showId=${info.showId}&cinemaId=${info.cinemaId}&movieId=${info.movieId}`,
        method: 'GET',
        success(res) {
          wx.hideLoading()
          resolve(res.data.data)
        },
        fail(err) {
          wx.hideLoading()
          reject(err)
        }
      })
    }).then(res => {
      wx.hideLoading()
      that.setData({
        seats: res.seats,
        maxSelect: res.restrictions
      })
      that.setSeat();
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  setSeat: function () {
    let yArray = [];
    let data = this.data.seats;

    //遍历座位信息中的 rowNo 行数，保存到 yArray 中
    for (let a = 0; a < data.length; a++) {

    }
    data.forEach(item => {
      item.forEach(i => {
        if (i.status == "N" && yArray.indexOf(i.rowNo) == -1) {
          yArray.push(i.rowNo);
        }
        if (i.status == 'W') { //过道或者没有座位
          i.iconSrc = "";
        } else {
          if (i.lovestatus == "0") {//单人座
            if (i.status == "N") {  // 未售
              i.iconSrc = "../../../image/icon/seatPre.png";//增加座位图片字段
              i.select = false;
            } else {  // 已售
              i.iconSrc = "../../../image/icon/seatDone.png";
              i.select = true;
            }
          } else {  // 情侣座
            if (i.status == "N") {  // 未售
              i.iconSrc = "../../../image/icon/qinglvwxz.png";//增加座位图片字段
              i.select = false;
            } else {  // 已售
              i.iconSrc = "../../../image/icon/qinglvxz.png";
              i.select = true;
            }
          }
        }
      })
    })
    this.setData({
      seat: data,
      lineArray: yArray,
      columnNumber: yArray.length
    })

    //与行号显示相关
    const query = wx.createSelectorQuery()
    query.select('#seatView').boundingClientRect()
    query.exec((res) => {
      let height = res[0].height;
      let newHeight = height / yArray.length;
      let top = res[0].top;
      this.setData({
        lineHeight: newHeight,
        lineTop: top
      })
    })
  },
  //movable-view相关
  onChange(e) {
    const query = wx.createSelectorQuery()
    query.select('#seatView').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res) => {
      //console.log(res);
      let height = res[0].height;
      let top = res[0].top;
      let newHeight = height / this.data.columnNumber;
      this.setData({
        lineHeight: newHeight,
        lineTop: top
      })
    })
  },
  onScale(e) {
    const query = wx.createSelectorQuery()
    query.select('#seatView').boundingClientRect()
    query.exec((res) => {
      //console.log(res);
      let height = res[0].height;
      let top = res[0].top;
      let newHeight = height / this.data.columnNumber;
      this.setData({
        lineHeight: newHeight,
        lineTop: top
      })
    })
  },
  //选座座位触发
  selectSeat(e) {
    let x = e.currentTarget.dataset.index + 1
    let y = e.currentTarget.dataset.ix + 1;
    let totalArray = this.data.seat;
    for (var a = 0; a < totalArray.length; a++) {
      for (var b = 0; b < totalArray[a].length; b++) {
        let item = totalArray[a][b];
        // if (item.rowNo == x && item.columnNo == y && item.status == 'N' && item.type != 'road') {
        if (item.rowNo == x && item.columnNo == y - 1 && item.status == 'N') {
          let totalMoney = 0.00;
          let totalMoneyStr = "";
          if (item.select == true) {
            item.select = false;
            item.iconSrc = item.lovestatus == '0' ? "../../../image/icon/seatPre.png" : "../../../image/icon/qinglvwxz.png";
            let seatInfo = item.seatNo;
            this.remove(seatInfo);
            totalMoney = (parseFloat(this.data.totalMoneyFloat) - parseFloat(item.settlePrice)).toFixed(2);
            totalMoneyStr = totalMoney.toString();
            if (totalMoney == 0) {
              totalMoneyStr = "";
            }
            this.setData({
              selectSeatList: this.data.selectSeatList,
              totalMoney: totalMoneyStr,
              totalMoneyFloat: totalMoney
            })
          } else {
            if (this.data.selectSeatList.length == this.data.maxSelect) {
              wx.showToast({
                title: `最多选择${this.data.maxSelect}个座位`,
                icon: 'none',
                duration: 1000,
                mask: true
              })
            } else {
              item.select = true;
              item.iconSrc = item.lovestatus == '0' ? "../../../image/icon/selectIcon.png" : '../../../image/icon/qinglvxz.png';

              let seat = {};
              let seatInfo = item.seatNo;
              seat.seatId = item.seatId;
              seat.areaId = item.areaId;
              seat.seatInfo = seatInfo;
              seat.lovestatus = item.lovestatus;

              seat.columnNo = item.columnNo;
              seat.rowNo = item.rowNo;
              seat.index = item.columnNo + item.rowNo;
              seat.settlePrice = item.settlePrice;
              seat.netPrice = item.netPrice;
              this.data.selectSeatList.push(seat);
              totalMoney = (parseFloat(this.data.totalMoneyFloat) + parseFloat(item.settlePrice)).toFixed(2);
              totalMoneyStr = totalMoney.toString();
              this.setData({
                selectSeatList: this.data.selectSeatList,
                totalMoney: totalMoneyStr,
                totalMoneyFloat: totalMoney
              })
            }

          }

        }
      }
    }
    this.setData({
      seat: totalArray
    })
  },
  //移除已选座座位信息
  remove(val) {
    for (var a = 0; a < this.data.selectSeatList.length; a++) {
      if (this.data.selectSeatList[a].seatInfo == val) {
        this.data.selectSeatList.splice(a, 1);
        break;
      }
    }
    this.setData({
      selectSeatList: this.data.selectSeatList
    })
  },
  //叉叉符号事件
  cancelSeat(e) {
    let index = e.currentTarget.dataset.index;
    let x = e.currentTarget.dataset.x;
    let y = e.currentTarget.dataset.y;
    let totalArray = this.data.seat;
    outerloop: for (var a = 0; a < totalArray.length; a++) {
      for (var b = 0; b < totalArray[a].length; b++) {
        console.log(1);
        if (totalArray[a][b].columnNo == y && totalArray[a][b].rowNo == x) {
          totalArray[a][b].select = false;
          totalArray[a][b].iconSrc = totalArray[a][b].lovestatus == '0' ? "../../../image/icon/seatPre.png" : "../../../image/icon/qinglvwxz.png";
          break outerloop;
        }
      }
    }
    let selectSeatList = this.data.selectSeatList
    for (var c = 0; c < selectSeatList.length; c++) {
      if (selectSeatList[c].index == index) {
        selectSeatList.splice(c, 1);
        break;
      }
    }
    let totalMoney = selectSeatList.map(i => Number(i.settlePrice)).reduce((d, e) => d + e, 0).toFixed(2);
    let totalMoneyStr = totalMoney.toString();
    if (totalMoney == 0) {
      totalMoneyStr = "";
    }
    this.setData({
      seat: totalArray,
      selectSeatList: selectSeatList,
      totalMoney: totalMoneyStr,
      totalMoneyFloat: totalMoney
    })
  },

  submit() {
    //添加订单信息
    const cinemaDetail = this.data.cinemaDetail;
    const movie = this.data.movie;
    const info = this.data.info;
    const selectSeatList = this.data.selectSeatList;
    if (selectSeatList.length < 1) {
      wx.showToast({
        icon: 'none',
        title: '请选择座位'
      })
      return
    }
    //判断左右两边不能为空
    let seats = this.data.seats;
    for (const item in selectSeatList) {
      const selectSeatBean = selectSeatList[item];
      const rowNo = selectSeatBean.rowNo;
      const columnNo = parseInt(selectSeatBean.columnNo);
      const seatList = seats[rowNo-1];
      //后面第一个座位
      const latterSeat = seatList[columnNo+1];
      //后面第二个座位
      const latterTwoSeat = seatList[columnNo+2];
      //前面第一个座位
      const previousSeat = seatList[columnNo-1];
      //前面第二个座位
      const previousTwoSeat = seatList[columnNo-2];

      if((previousSeat.select == false) && (typeof previousTwoSeat === 'undefined' || previousTwoSeat.select == true || previousTwoSeat.status == 'W')){
        wx.showToast({
          icon: 'none',
          title: '左右两边的座位不能留空'
        })
        return
      }
      if(typeof latterSeat != 'undefined'){
        if((latterSeat.select == false) && (typeof latterTwoSeat === 'undefined' || latterTwoSeat.select == true || latterTwoSeat.status == 'W')){
          wx.showToast({
            icon: 'none',
            title: '左右两边的座位不能留空'
          })
          return
        }
      }
      
    }


    if (selectSeatList.length < 1) {
      wx.showToast({
        icon: 'none',
        title: '请选择座位'
      })
      return
    }

    if (!app.globalData.userInfo || app.globalData.userInfo == '{}') {
      wx.showModal({
        content: '您还未登录',
        success(res) {
          wx.switchTab({
            url: '/pages/user/user',
          })
        }
      })
    }
    console.log(selectSeatList);
    let areaIds = selectSeatList.map(i => i.areaId)
    for (let i = 0; i < areaIds.length; i++) {
      if (areaIds.indexOf(areaIds[i]) < 0) {
        wx.showToast({
          icon: 'none',
          title: '请选择同一价格的位置，暂不支持跨区选座'
        })
        return
      }
    }

    let paramsStr = {
      cinemaName: cinemaDetail.nm,//电影院名
      cinemaId: info.cinemaId,//电影院ID
      cinemaAddr: cinemaDetail.addr,//电影院地址
      hall: info.hallName,//大厅
      movieName: movie.name,//电影名
      movieImg: movie.pic,//海报
      movieId: movie.movieId,
      grade: movie.grade,
      duration: movie.duration,
      // timesId:info.id,
      time: info.showTime,//时间
      price: this.data.settlePrice,//票价
      loveStatus: selectSeatList[0].loveStatus, // 是否情侣座位
      seatIds: selectSeatList.map(item => item.seatId), // 座位id
      seatNo: selectSeatList.map(item => item.seatInfo), // 座位名称
      showId: info.showId, // 场次Id
      ticketNum: selectSeatList.length,  // 选中的座位数
      ticketUnitPrice: selectSeatList[0].settlePrice,  // 特惠票价
      ticketOriginalPrice: selectSeatList[0].netPrice,  // 原本票价
      totalPrice: this.data.totalMoney,//票价
      consumerId: app.globalData.userInfo.consumerId,
      appid: wx.getAccountInfoSync().miniProgram.appId
    }
    //用户确认座位
    wx.showLoading();
    wx.request({
      url: app.globalData.url + `/movieOrder/confirmSeats`,
      method: 'POST',
      data: paramsStr,
      header: {
        consumerId: app.globalData.userInfo.consumerId
      },
      success(res) {
        wx.hideLoading();
        if (res.data.code === 200) {
          paramsStr = JSON.stringify({
            ...paramsStr,
            orderNo: res.data.data.orderNo,
            payTimeEnd: res.data.data.payTimeEnd,
            ticketOriginalPrice: res.data.data.netPrice, // 原本票价
            ticketUnitPrice: res.data.data.settlePrice,  // 特惠票价
          });
          // console.log(paramsStr);
          wx.navigateTo({
            url: `/pages/subPages/buy-ticket/buy-ticket?paramsStr=${encodeURIComponent(paramsStr)}`,
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
          })
        }
      },
      fail(err) {
        reject(err)
      }
    })

  }

})